package com.fat.spzx.manager.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.fat.spzx.common.constans.RedisConstans;
import com.fat.spzx.manager.service.ValidateCodeService;
import com.fat.spzx.model.vo.system.ValidateCodeVo;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class ValidateCodeServiceImpl implements ValidateCodeService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 生成验证码
     * @return
     */
    @Override
    public ValidateCodeVo generateValidateCode() {
        //1.生成验证码
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(150, 48, 4, 20);
        String codeKey = circleCaptcha.getCode();
        String base64 = circleCaptcha.getImageBase64();

        //2.将验证码存入redis
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        redisTemplate.opsForValue().set(RedisConstans.USER_LOGIN_VALIDATECODE +uuid,codeKey,2, TimeUnit.MINUTES);

        //3.将验证码封装在VO返回
        ValidateCodeVo validateCodeVo = new ValidateCodeVo();
        validateCodeVo.setCodeKey(uuid);
        validateCodeVo.setCodeValue("data:image/png;base64," +base64);

        return validateCodeVo;
    }
}
